用 + 作為合併陣列,你要注意的是 + , it does not append or merge.
如果覺得合併陣列使用 + ,就能將兩個陣列合併在一起,你可能會失望.
我以為 [1]+[2] output [1,2],但是 output [1]
我以為的 + 在陣列是合併的效果,例如:
<?php
$a = [1, 2, 3];
$b = [5, 6, 7];
$c = $a + $b;
return $c;
// 我以為的      $c: [1, 2, 3, 5, 6, 7]
// 實際拿到的    $c: [1, 2, 3]
自以為的 和 實際拿到的 $c 結果相異:
$foo)的變數值 覆蓋 前寫的變數值,顯然 + 的覆蓋方式並不是先後順序的<?php
$foo = "hello";
$foo = "world!";
return $foo; // "world!"
+ operator 在陣列中,代表的是什麼意思,參考 What is the difference between array_merge and array + array in PHP?+ 作為運算符號時,+ 視作 union operator ,意指,它(+) 一次合併兩個陣列。 union operator 將右側陣列附加到左側陣列的末尾$c: [1, 2, 3] 為正解。<?php
/* 依照 element index 順序,陣列 $a 排序:
 * Array $a = (
 *  [0] => 1,
 *  [1] => 2,
 *  [2] => 3
 * )
 */ 
/* 依照 element index 順序,陣列 $b 排序:
 * Array $b = (
 *  [0] => 5,
 *  [1] => 6,
 *  [2] => 7
 * )
 */ 
使用 + 合併陣列,雖說 + 是 union operator,但是使用上,又和數學上的 union (聯集) 存在差異,例如,左側 array key 或 element index 相同於右側,則左側陣列 value 覆蓋 右側陣列 value (數學上的聯集應是一同輸出左側陣列 value 和右側陣列 value)。
1 What is the difference between array_merge and array + array in PHP?
2 Array Operators
3 PHP Arrays
4 Merging two arrays with the "+" (array union operator) How does it work?
5 array_merge vs array_replace vs + (plus aka union) in PHP